package com.leyou.item.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.Spu;
import com.leyou.item.mapper.LyBaseMapper;
import com.leyou.item.mapper.lymapper.SpuMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.SpuService;
import com.leyou.item.service.base.AbstractBaseService;
import com.leyou.item.vo.PageResult;
import com.leyou.item.vo.SpuVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author linzx
 * @date 2020/3/25
 */
@Service
public class SpuServiceImpl extends AbstractBaseService<Spu> implements SpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;

    @Override
    protected LyBaseMapper<Spu> getMapper() {
        return spuMapper;
    }

    @Override
    public PageResult<SpuVO> querySpuPage(String key, Boolean saleable, Integer page, Integer rows) {

        PageHelper.startPage(page,rows);
        Example example = new Example(Spu.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().orLike("title","%"+ key + "%") ;
        }
        if (saleable != null) {
            example.createCriteria().andEqualTo("saleable",saleable);
        }
        List<Spu> spus = selectByExample(example);
        PageInfo<Spu> spuPageInfo = new PageInfo<>(spus);
        List<SpuVO> spuVOList = new ArrayList<>();
        spus.forEach(spu -> {
            SpuVO spuVO = new SpuVO();
            BeanUtils.copyProperties(spu,spuVO);
            List<String> cnames = categoryService.selectByIdList(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()))
                    .stream().map(Category::getName).collect(Collectors.toList());
            spuVO.setCname(StringUtils.join(cnames,"/"));
            spuVO.setBname(brandService.selectByPrimaryKey(spu.getBrandId()).getName());
            spuVOList.add(spuVO);
        });

        return new PageResult<>(spuPageInfo.getTotal(),spuVOList);
    }
}
